<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="民族" prop="nationality">
        <el-select v-model="queryParams.nationality" placeholder="请选择民族" clearable size="small">
          <el-option
            v-for="dict in nationalityOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNum">
        <el-input
          v-model="queryParams.idCardNum"
          placeholder="请输入身份证号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属行政区划" prop="asdsId">
        <el-input
          v-model="queryParams.idCardNum"
          placeholder="请输入所属行政区划"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属社区" prop="community">
        <el-select v-model="queryParams.community" placeholder="请选择所属社区" clearable size="small">
          <el-option label="请选择字典生成" value=""/>
        </el-select>
      </el-form-item>
      <el-form-item label="全国学籍号" prop="schoolRollNum">
        <el-input
          v-model="queryParams.schoolRollNum"
          placeholder="请输入全国学籍号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input
          v-model="queryParams.gender"
          placeholder="请输入性别"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker clearable size="small"
                        v-model="queryParams.birthday"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择出生日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['swallow:student:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['swallow:student:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['swallow:student:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['swallow:student:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="出生日期" align="center" prop="id"/>
      <el-table-column label="姓名" align="center" prop="name"/>
      <el-table-column label="身份证号" align="center" prop="idCardNum"/>
      <el-table-column label="所属行政区划" align="center" prop="asds.name"/>
      <el-table-column label="所属社区" align="center" prop="community"/>
      <el-table-column label="全国学籍号" align="center" prop="schoolRollNum"/>
      <el-table-column label="性别" align="center" prop="gender" :formatter="genderFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['swallow:student:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['swallow:student:remove']"
          >删除
          </el-button>&emsp;
          <el-popover placement="left" width="400" trigger="click" @show="getJhrList(scope.row)">
            <p v-for="item in jhrList">{{jhrgxFormat(item.gx)}}&emsp;|
              <el-button @click="jhrUpdate(item)" type="text">{{item.xm}}</el-button>
            </p>
            <el-button @click="jhrAdd(scope.row)">新增监护人</el-button>
            <el-button
              v-hasPermi="['swallow/jhr/index']"
              size="mini"
              type="text"
              icon="el-icon-s-custom"
              slot="reference"

            >监护人
            </el-button>
          </el-popover>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body :close-on-click-modal="false" :close-on-press-escape=false >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="民族" prop="nationality">
          <el-select  v-model="form.nationality" filterable placeholder="请选择民族">
            <el-option
              v-for="dict in nationalityOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNum">
          <el-input v-model="form.idCardNum" placeholder="请输入身份证号"/>
        </el-form-item>
        <el-form-item label="所属行政区划" prop="asdsId">
          <!--<el-input v-model="form.asdsId" placeholder="请输入所属行政区划" />-->
          <!-- :disable-branch-nodes="true" 属性是设置只能选择末级单位-->
          <treeselect v-model="form.asdsId" :options="asdsOptions" :disable-branch-nodes="true" placeholder="请选择所属行政区划" :normalizer="normalizer"/>
        </el-form-item>
        <el-form-item label="所属社区" prop="community">
          <el-select v-model="form.community" placeholder="请选择所属社区">
            <el-option label="请选择字典生成" value=""/>
          </el-select>
        </el-form-item>
        <el-form-item label="详细住址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细住址"/>
        </el-form-item>
        <el-form-item label="全国学籍号" prop="schoolRollNum">
          <el-input v-model="form.schoolRollNum" placeholder="请输入全国学籍号" type="number"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请输入性别">
            <el-option
              v-for="dict in genderOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker clearable size="small"
                          v-model="form.birthday"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--添加或修改学生监护人对话框-->
    <el-dialog :title="jhrTitle" :visible.sync="jhrOpen" width="500px" append-to-body>
      <el-form ref="jhrForm" :model="jhrForm" :rules="jhrRules" label-width="80px">
        <el-form-item label="与学生关系" prop="gx">
          <el-select v-model="jhrForm.gx" placeholder="请选择与学生关系">
            <el-option
              v-for="dict in gxOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="xm">
          <el-input v-model="jhrForm.xm" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="民族" prop="mz">
          <!--<el-input v-model="jhrForm.mz" placeholder="请输入民族" />-->
          <el-select v-model="jhrForm.mz" placeholder="民族">
            <el-option
              v-for="dict in mzOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="sfzh">
          <el-input v-model="jhrForm.sfzh" placeholder="请输入身份证号"/>
        </el-form-item>
        <!--<el-form-item label="所属社区" prop="sssq">
          <el-input v-model="jhrForm.sssq" placeholder="请输入所属社区" />
        </el-form-item>-->
        <!--<el-form-item label="详细住址" prop="xxzz">
          <el-input v-model="jhrForm.xxzz" placeholder="请输入详细住址" />
        </el-form-item>-->
        <el-form-item label="性别" prop="xb">
          <!--<el-input v-model="jhrForm.xb" placeholder="请输入性别" />-->
          <el-select v-model="jhrForm.xb" placeholder="请输入性别">
            <el-option v-for="dict in xbOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue">

            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="csrq">
          <el-date-picker clearable size="small"
                          v-model="jhrForm.csrq"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择出生日期">
          </el-date-picker>
        </el-form-item>
        <!--<el-form-item label="居住地行政区划id，来自于fx_administrative_divisions表" prop="jzdAsdsId">
          &lt;!&ndash;<el-input v-model="jhrForm.jzdAsdsId" placeholder="请输入居住地行政区划" />&ndash;&gt;
          <treeselect v-model="jhrForm.jzdAsdsId" :options="asdsOptions"  placeholder="请选择所属行政区划" :normalizer="normalizer"/>
        </el-form-item>-->
        <el-form-item label="手机号" prop="sj">
          <el-input v-model="jhrForm.sj" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="jhrForm.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitJhrForm">确 定</el-button>
        <el-button @click="jhrCancel()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listStudent,
    listStudentVo,
    getStudent,
    delStudent,
    addStudent,
    updateStudent,
    exportStudent
  } from "@/api/swallow/student";
  import {listAsds} from "@/api/swallow/asds";
  import {selectByStudent, listJhr, getJhr, delJhr, addJhr, updateJhr, exportJhr} from "@/api/swallow/jhr";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "Student",
    components: {Treeselect},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        //选中学生的姓名
        names:[],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 学生表格数据
        studentList: [],
        // 弹出层标题
        title: "",

        // 是否显示弹出层
        open: false,

        // 民族。来自于数据字典字典
        nationalityOptions: [],
        // 性别。来自于数据字典字典
        genderOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          nationality: null,
          idCardNum: null,
          community: null,
          schoolRollNum: null,
          gender: null,
          birthday: null,
          asdsId: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          createBy: [
            {required: true, message: "出生日期不能为空", trigger: "blur"}
          ],
          createTime: [
            {required: true, message: "出生日期不能为空", trigger: "blur"}
          ],
          updateTime: [
            {required: true, message: "出生日期不能为空", trigger: "blur"}
          ],
          name: [
            {required: true, message: "姓名不能为空", trigger: "blur"}
          ],
          idCardNum: [
            {required: true, message: "身份证号不能为空", trigger: "blur"}
          ],
          asdsId: [
            {required: true, message: "所属行政区划不能为空", trigger: "blur"}
          ],
        },
        // 部门树选项
        asdsOptions: [],
        // 监护人列表
        jhrList: [],
        jhrGxOptions: [],
        //监护人弹出层标题
        jhrTitle: "",
        //是否弹出监护人列表弹出层
        jhrOpen: false
        //监护人表单
        , jhrForm: {}
        //监护人表单校验
        , jhrRules: {
          gx: [
            {required: true, message: "与学生关系，缘字字典表，“qsgx”不能为空", trigger: "change"}
          ],
          xm: [
            {required: true, message: "姓名不能为空", trigger: "blur"}
          ],
          sfzh: [
            {required: true, message: "身份证号不能为空", trigger: "blur"}
          ],
        }
        , gxOptions: []
        , mzOptions: []
        , xbOptions: []
      };
    },
    created() {
      this.getList();
      this.getAsdsTreeselect();
      this.getDicts("fx_nationality ").then(response => {
        this.nationalityOptions = response.data;
      });
      this.getDicts("sys_user_sex").then(response => {
        this.genderOptions = response.data;
      });
      this.getDicts("qsgx").then(response => {
        this.jhrGxOptions = response.data;
      });
      this.getDicts("qsgx").then(response => {
        this.gxOptions = response.data;
      });
      this.getDicts("fx_nationality ").then(response => {
        this.mzOptions = response.data;
      });
      this.getDicts("sys_user_sex ").then(response => {
        this.xbOptions = response.data;
      });
    },
    methods: {
      /** 查询学生列表 */
      getList() {
        this.loading = true;
        listStudentVo(this.queryParams).then(response => {
          this.studentList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 民族。来自于数据字典字典翻译
      nationalityFormat(row, column) {
        return this.selectDictLabel(this.nationalityOptions, row.nationality);
      },
      // 性别。来自于数据字典字典翻译
      genderFormat(row, column) {
        return this.selectDictLabel(this.genderOptions, row.gender);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          name: null,
          nationality: null,
          idCardNum: null,
          asdsId: null,
          community: null,
          address: null,
          schoolRollNum: null,
          gender: null,
          birthday: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        console.log(JSON.stringify(selection))
        this.ids = selection.map(item => item.id)
        this.names=selection.map(item=>item.name)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加学生";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        console.log(JSON.stringify(this.ids))
        getStudent(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改学生";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateStudent(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addStudent(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        const names=row.name||this.names;
        this.$confirm('是否删除“'+names+'”，且删除其所有已录入的监护人？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delStudent(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },

      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有学生数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportStudent(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 查询所属行政区划下拉树结构 */
      /*getTreeselect() {
        treeselect().then(response => {
          var asdsOptions=response.data;
          this.removeInvalidData(asdsOptions)
          this.asdsOptions =asdsOptions;
        });
      },
      //去除无用数据
      removeInvalidData(data){
        for (let i = 0; i < data.length; i++) {
          var item =data[i];
          if(item.children==null || item.children.length==0){
            delete data[i].children;
          }else{
            this.removeInvalidData(data[i].children);
          }

        }
      }*/

      /** 查询所属行政机构下拉树结构 */
      getAsdsTreeselect() {
        listAsds().then(response => {
          this.asdsOptions = this.handleTree(response.data, "id", "parentId");
        });
      },
      /** 转换行政区划数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      //获取当前学生的监护人
      getJhrList(row) {
        selectByStudent(row.id).then(respons => {
          this.jhrList = respons;
        })
      },
      /**监护人关系Format*/
      jhrgxFormat: function (gxCode) {
        return this.selectDictLabel(this.jhrGxOptions, gxCode);
      },
      /*监护人修改按钮*/
      jhrUpdate(jhr) {
        this.jhrFormReset();
        getJhr(jhr.id).then(response => {
          this.jhrForm = response.data;
          this.jhrOpen = true;
          this.jhrTitle = "修改学生监护人";
        });
      },
      /*提交监护人表单*/
      submitJhrForm(){
        console.log("this.jhrForm.xsId="+this.jhrForm.xsId)
        this.$refs["jhrForm"].validate(valid => {
          if (valid) {
            if (this.jhrForm.id != null) {
              updateJhr(this.jhrForm).then(response => {
                this.msgSuccess("修改成功");
                this.jhrOpen = false;
              });
            } else {
              addJhr(this.jhrForm).then(response => {
                this.msgSuccess("新增成功");
                this.jhrOpen = false;
              });
            }
          }
        });
      },
      /*表单重置*/
      jhrFormReset() {
        this.jhrForm = {
          id: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          xsId: null,
          gx: null,
          xm: null,
          mz: null,
          sfzh: null,
          sssq: null,
          xxzz: null,
          xb: null,
          csrq: null,
          jzdAsdsId: null,
          sj: null
        };
        this.resetForm("jhrForm");
      },
      /*监护人新增按钮*/
      jhrAdd(row) {
        this.jhrFormReset();
        this.jhrForm.xsId=row.id;
        this.jhrOpen = true;
        this.jhrTitle = "添加学生监护人";
      },
      /*监护人新增弹窗的取消按钮*/
      jhrCancel() {
        this.jhrOpen = false;
        this.jhrFormReset();
      },
    }
  };
</script>
